package com.fuyao.cloud.common.excel.handler;

import com.alibaba.excel.context.AnalysisContext;
import com.fuyao.cloud.common.excel.kit.Validators;
import com.fuyao.cloud.common.excel.vo.ErrorMessage;
import lombok.extern.slf4j.Slf4j;

import javax.validation.ConstraintViolation;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 不创建对象获取数据
 */
@Slf4j
public class CustomColEventListener extends ListAnalysisEventListener<Map<Integer,String>>{

    private final List<Map<Integer,String>> list = new ArrayList<>();

    private final List<ErrorMessage> errorMessageList = new ArrayList<>();

    private Long lineNum = 0L;

    @Override
    public List<ErrorMessage> getErrors() {
        return errorMessageList;
    }

    @Override
    public void invoke(Map<Integer,String> data, AnalysisContext context) {
        lineNum++;
        Set<ConstraintViolation<Object>> violations = Validators.validate(data);
        if (!violations.isEmpty()) {
            Set<String> messageSet = violations.stream().map(ConstraintViolation::getMessage)
                    .collect(Collectors.toSet());
            errorMessageList.add(new ErrorMessage(lineNum, messageSet));
        } else {
            list.add(data);
        }
    }

    /**
     * 获取表头数据到头部
     * @param headMap
     * @param context
     */
    @Override
    public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
        list.add(headMap);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        log.debug("Excel read analysed");
    }

    @Override
    public List<Map<Integer,String>> getList() {
        return list;
    }
}
